//
//  CagooController.m
//
//  Created by brice rouanet on 04/02/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "CagooController.h"
#import "CagooConfig.h"
#import "CagooPref.h"

#define SGApplicationPath @"/Applications/CagooCmd.app"

@implementation CagooController (PrivateMethods)
- (void)enableLoginItemWithLoginItemsReference:(LSSharedFileListRef )theLoginItemsRefs ForPath:(CFURLRef)thePath {
	// We call LSSharedFileListInsertItemURL to insert the item at the bottom of Login Items list.
	LSSharedFileListItemRef item = LSSharedFileListInsertItemURL(theLoginItemsRefs, kLSSharedFileListItemLast, NULL, NULL, thePath, NULL, NULL);
	if (item)
		CFRelease(item);
}

- (void)disableLoginItemWithLoginItemsReference:(LSSharedFileListRef )theLoginItemsRefs ForPath:(CFURLRef)thePath {
	UInt32 seedValue;
	
	// We're going to grab the contents of the shared file list (LSSharedFileListItemRef objects)
	// and pop it in an array so we can iterate through it to find our item.
	NSArray *loginItemsArray = (NSArray *)LSSharedFileListCopySnapshot(theLoginItemsRefs, &seedValue);
	NSLog(@"item enabled to disabled %@\n",loginItemsArray);
	for (id item in loginItemsArray) {
		LSSharedFileListItemRef itemRef = (LSSharedFileListItemRef)item;
		if (LSSharedFileListItemResolve(itemRef, 0, (CFURLRef*) &thePath, NULL) == noErr) {
			if ([[(NSURL *)thePath path] hasPrefix:SGApplicationPath])
				LSSharedFileListItemRemove(theLoginItemsRefs, itemRef); // Deleting the item
		}
	}
	
	[loginItemsArray release];
}
@end


@implementation CagooController
- (IBAction)onClickActivate:(id)sender {
    
}

- (IBAction)onClickDeactivate:(id)sender {
    
}

- (IBAction)enableCagoo:(id)sender {
	
	CFURLRef url = (CFURLRef)[NSURL fileURLWithPath:SGApplicationPath];
	
	// Create a reference to the shared file list.
	LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL);

	if ([theEnable  state] == NSOnState)
	{
		NSLog(@"Enable Cagoo %@\n",url);
		[self enableLoginItemWithLoginItemsReference:loginItems ForPath:url];
		//copy pref file
		char path[255]="/Users/";
		strcat(path,getenv("USER"));
		strcat(path,"/Library/Preferences/loginwindow.plist");

		
		char *cpArgs[] = {path,"/System/Library/User Template/French.lproj/Library/Preferences/", NULL};
		AuthorizationExecuteWithPrivileges(authorizationRef,"/bin/cp", kAuthorizationFlagDefaults, cpArgs, NULL);
	}
	else
	{
		NSLog(@"Disable Cagoo %@\n",url);
		[self disableLoginItemWithLoginItemsReference:loginItems ForPath:url];
		//remove pref file
		char *rmArgs[] = {"/System/Library/User Template/French.lproj/Library/Preferences/loginwindow.plist", NULL};
		AuthorizationExecuteWithPrivileges(authorizationRef,"/bin/rm", kAuthorizationFlagDefaults, rmArgs, NULL);
		
	}
	
	 CFRelease(loginItems);
}

- (IBAction)minusCagoo:(id)sender {
	
	//remove item from array
	[viewBuffer removeObjectAtIndex:[theTable selectedRow]];
	[theTable reloadData];

}

- (IBAction)plusCagoo:(id)sender {
	//add the textfield content in the array
	int	row;
	
	if (!viewBuffer)
		return;
	
	//	Add an untitled part to the list
	
	row = [theTable selectedRow];
	

	
	NSString *theNewString = [NSString stringWithFormat:@"%@@%@",[theTextField stringValue],[theTextField2 stringValue] ];
	
	if (row < 0) {

		//	No selection: append
		row = [viewBuffer count]-1;
		[viewBuffer insertObject:theNewString  atIndex:row];

	}
	else {
		[viewBuffer insertObject:theNewString  atIndex:row];
	}
	
	//	Tell the table we've changed
	[theTable reloadData];
	
}

- (IBAction)saveCagoo:(id)sender {
	
	//prepare save bufer
	NSMutableArray *saveBuffer = [NSMutableArray new];
	
	saveBuffer = viewBuffer;
	
	if ([theEnable  state] == NSOnState)
		[saveBuffer insertObject:@"cagooEnabled=TRUE"  atIndex:0];
	else {
		[saveBuffer insertObject:@"cagooEnabled=FALSE"  atIndex:0];
	}

	//write file
	CagooConfig *conf = [CagooConfig alloc];
	[conf saveConf:saveBuffer];

}

- (int)numberOfRowsInTableView:(NSTableView *)theTable{
	return ([viewBuffer count]);
}

- (id)tableView:(NSTableView *)theTable objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)row{
		
	return [viewBuffer objectAtIndex:row];
}

	
-(void)setCheckboxEnabled:(BOOL)isEnabled
{
	if (isEnabled == TRUE)
	{
		[theEnable setState:NSOnState];
	}
	else
	{
		[theEnable setState:NSOffState];
	}
	
}



- (void)awakeFromNib{
	

	
	//ask sudo privileges
	NSLog(@"start1\n");
	
	
	mkdir("/Library/Application Support/Cagoo",0755);
	
	FILE *file;
	
	file=fopen("/Library/Application Support/Cagoo/cagoo.conf","r");
	if (file == NULL)
	{
		NSLog(@"Error opening conf file file\n");
		//creating file
		NSArray *baseConf = [NSArray arrayWithObjects:@"cagooEnabled=FALSE",@"//192.168.1.1/home/$LOGNAME@/Users/$LOGNAME",nil];
		[baseConf writeToFile:@"/Library/Application Support/Cagoo/cagoo.conf" atomically:YES];
		chmod("/Library/Application Support/Cagoo/cagoo.conf", 0777);
	}
	
	fclose(file);
	
	
	//test if conf file exist, else create it	
		NSLog(@"start2\n");
	viewBuffer = [NSMutableArray new];
	[theTable reloadData];
	[theTable setDataSource:self];
	
	//read config file
	CagooConfig *conf = [CagooConfig alloc];
	
	//set or not the textbox
	if ([conf isCagooEnabled])
	{
		NSLog(@"cagoo is enabled\n");
		[self setCheckboxEnabled:TRUE];
	}
	else {
		NSLog(@"cagoo is no enabled or there is an error in conf file\n");
		[self setCheckboxEnabled:FALSE];
	}
	

	viewBuffer = conf->tableContent;
	[viewBuffer removeObjectAtIndex:0];

	[theTable reloadData];
		
	
}

- (void)dealloc {
	[viewBuffer release];
	[super dealloc];
}

- (IBAction)clickOnTable:(id)sender {
    NSLog(@"hehe\n");
}
@end
